mongoStore = require('../mongoStore')
log = require('../log')
mongoChain = require('../mongoChain')

errors = require('../errors')

gCollectionTopic = ->
    db = yield mongoStore.gDatabase()
    db.collection 'topic'

exports.gCreateTopic = (body)->
    col = yield from gCollectionTopic()
    r = yield col.insertOne body

exports.gListTopics = (query)->
    col = yield from gCollectionTopic()
    r = mongoStore.find(query, col)
    page = yield r.toArray()
    total = r.count()
    return {total, page: page}

exports.gGetTopicById = (id)->
    col = yield from gCollectionTopic()
    _id = mongoStore.stringToObjectId(id)
    r = yield col.findOne({_id})
    return r

exports.gDeleteTopic = (id)->
    col = yield from gCollectionTopic()
    id = mongoStore.stringToObjectId(id)
    yield col.deleteOne({_id: id})

exports.gEditTopic = (id, body, userId)->
    col = yield from gCollectionTopic()
    _id = mongoStore.stringToObjectId(id)
    topic = yield col.findOne({_id})
    if topic
        console.log topic
        throw new errors.UserError("TopicNotFound") if topic.userId != userId

        yield col.updateOne({_id}, body)